import * as Cesium from 'cesium';

class positionTransfer {
  constructor(viewer) {
    this.viewer = viewer;
  }
  // 经纬度转笛卡尔坐标
  cartesion3ToLng(position) {
    // console.log('Received position:', position);

    if (!position || !(position instanceof Cesium.Cartesian3)) {
      throw new Error('Invalid position: Must be a valid Cartesian3 object');
    }
    //获取当前椭球的坐标系统,其中包含了坐标转换工具
    const ellipsoid = this.viewer.scene.globe.ellipsoid;
    //将笛卡尔坐标转为弧度坐标
    const cartoGraphic = ellipsoid.cartesianToCartographic(position);
    //将弧度坐标转为经纬度坐标
    const lng = Cesium.Math.toDegrees(cartoGraphic.longitude);
    const lat = Cesium.Math.toDegrees(cartoGraphic.latitude);
    const height = cartoGraphic.height;
    return { lng, lat, height };
  }

  //经纬度转笛卡尔
  lngToCartesion3(position) {
    const { lng, lat, height } = position;
    return Cesium.Cartesian3.fromDegrees(lng, lat, height);
  }

  //将批量的经纬度转为笛卡尔
  lngPositionsToCartesion3(positions, isHeight = false) {
    const resArr = [];
    positions.forEach(position => {
      const { lng, lat, height } = position;
      if (isHeight) {
        resArr.push(lng, lat, height);
      } else {
        resArr.push(lng, lat);
      }
    });
    return isHeight ? new Cesium.Cartesian3.fromDegreesArrayHeights(resArr) : new Cesium.Cartesian3.fromDegreesArray(resArr);
  }

  //屏幕坐标与笛卡尔坐标的转换
  screenToCartesian3(position) {
    return this.viewer.scene.globe.pick(this.viewer.camera.getPickRay(position), this.viewer.scene);
  }

  //世界坐标转换屏幕坐标
  cartesian3ToScreen(position) {
    return Cesium.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene, position);
  }

  //todo:世界坐标转为带地形的经纬度坐标
}

export default positionTransfer;
